package cn.itrip.biz.controller;

import cn.itrip.beans.dtos.Dto;
import cn.itrip.beans.pojo.*;
import cn.itrip.beans.vo.order.*;
import cn.itrip.biz.service.itripHotel.ItripHotelService;
import cn.itrip.biz.service.itripHotelOrder.ItripHotelOrderService;
import cn.itrip.biz.service.itripHotelRoom.ItripHotelRoomService;
import cn.itrip.biz.service.itripOrderLinkUser.ItripOrderLinkUserService;
import cn.itrip.common.*;
import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/api/hotelorder")
public class HotelOrderController {
    @Resource
    private ValidationToken validationToken;
    @Resource
    private ItripHotelService itripHotelService;
    @Resource
    private ItripHotelRoomService itripHotelRoomService;
    @Resource
    private ItripHotelOrderService itripHotelOrderService;
    @Resource
    private SystemConfig systemConfig;
    @Resource
    private ItripOrderLinkUserService itripOrderLinkUserService;


    @RequestMapping(value = "/getpredorderinfo", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Dto<RoomStoreVO> getPreOrderInfo(@RequestBody ValidateRoomStoreVO validateRoomStoreVO, HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        String agent = request.getHeader("user-agent");
        try {
            if(!validationToken.validateToken(token, agent)){
                return DtoUtil.returnFail("token失效，请重登录", "100000 ");
            }
            if(validateRoomStoreVO.getHotelId() == null || validateRoomStoreVO.getHotelId() == 0){
                return DtoUtil.returnFail("hotelId不能为空", "100510 ");
            }
            if(validateRoomStoreVO.getRoomId() == null || validateRoomStoreVO.getRoomId() == 0){
                return DtoUtil.returnFail("roomId不能为空", "100511 ");
            }
            if(validateRoomStoreVO.getCheckInDate() == null || validateRoomStoreVO.getCheckOutDate() == null){
                return DtoUtil.returnFail("入住和退房时间不能为空", "100514");
            }
            if(validateRoomStoreVO.getCheckInDate().getTime() > validateRoomStoreVO.getCheckOutDate().getTime()){
                return DtoUtil.returnFail("入住时间不能晚于退房时间","100514");
            }

            ItripHotel hotel = itripHotelService.getItripHotelById(validateRoomStoreVO.getHotelId());
            ItripHotelRoom room = itripHotelRoomService.getItripHotelRoomById(validateRoomStoreVO.getRoomId());
            RoomStoreVO roomStoreVO = new RoomStoreVO();
            roomStoreVO.setCheckInDate(validateRoomStoreVO.getCheckInDate());
            roomStoreVO.setCheckOutDate(validateRoomStoreVO.getCheckOutDate());
            roomStoreVO.setCount(1);
            roomStoreVO.setHotelId(hotel.getId());
            roomStoreVO.setHotelName(hotel.getHotelName());
            roomStoreVO.setRoomId(room.getId());
            roomStoreVO.setPrice(BigDecimal.valueOf(room.getRoomPrice()));
//          roomStoreVO.setStore();
            Map<String, Object> param = new HashMap<>();
            param.put("startTime",validateRoomStoreVO.getCheckInDate());
            param.put("endTime",validateRoomStoreVO.getCheckOutDate());
            param.put("roomId",validateRoomStoreVO.getRoomId());
            param.put("hotelId",validateRoomStoreVO.getHotelId());
            List<ItripHotelTempStore> result = itripHotelOrderService.queryRoomStore(param);
            if(EmptyUtils.isEmpty(result)){
                return DtoUtil.returnFail("暂时无房","100512");
            }else{
                roomStoreVO.setStore(result.get(0).getStore());
                return DtoUtil.returnDataSuccess(roomStoreVO);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("系统异常", "100513");
        }
    }

    @RequestMapping(value = "/validateroomstore", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    //key:flag
    public Dto<Map<String, Boolean>> validateRoomStore(@RequestBody ValidateRoomStoreVO validateRoomStoreVO,
                                                       HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        String agent = request.getHeader("user-agent");
        try {
            if(!validationToken.validateToken(token, agent)){
                return DtoUtil.returnFail("token失效，请重登录", "100000");
            }
            if(validateRoomStoreVO.getHotelId() == null || validateRoomStoreVO.getHotelId() == 0){
                return DtoUtil.returnFail("hotelId不能为空", "100515");
            }
            if(validateRoomStoreVO.getRoomId() == null || validateRoomStoreVO.getRoomId() == 0){
                return DtoUtil.returnFail("roomId不能为空", "100516");
            }
            if(validateRoomStoreVO.getCheckInDate() == null || validateRoomStoreVO.getCheckOutDate() == null){
                return DtoUtil.returnFail("入住和退房时间不能为空", "100514");
            }
            if(validateRoomStoreVO.getCheckInDate().getTime() > validateRoomStoreVO.getCheckOutDate().getTime()){
                return DtoUtil.returnFail("入住时间不能晚于退房时间","100514");
            }
            if(validateRoomStoreVO.getCount() == null || validateRoomStoreVO.getCount() == 0){
                return DtoUtil.returnFail("需要输入房间数","100518");
            }

            Map<String, Object> param = new HashMap<>();
            param.put("startTime",validateRoomStoreVO.getCheckInDate());
            param.put("endTime",validateRoomStoreVO.getCheckOutDate());
            param.put("roomId",validateRoomStoreVO.getRoomId());
            param.put("hotelId",validateRoomStoreVO.getHotelId());
            param.put("count",validateRoomStoreVO.getCount());
            //第一种需求
            boolean result = itripHotelOrderService.validateRoomStore(param);
            if(result){
                Map<String, Boolean> output = new HashMap<>();
                output.put("success",result);
                return DtoUtil.returnDataSuccess(output);

//                //第二种需求，加入实际库存数
//                Map<String, Object> output2 = itripHotelOrderService.validateRoomStore2(param);
//                return DtoUtil.returnDataSuccess(output2);
            }else{
                return DtoUtil.returnFail("暂时无房","100512");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("系统异常", "100517");
        }
    }

    @RequestMapping(value = "/addhotelorder", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Dto<Map<String,String>> addHotelOrder(@RequestBody ItripAddHotelOrderVO itripAddHotelOrderVO, HttpServletRequest request) throws Exception{
        try{
            //验证token
            String token = request.getHeader("token");
            String agent = request.getHeader("user-agent");
            if(!validationToken.validateToken(token, agent)){
                return DtoUtil.returnFail("token失效，请重登录", "100000");
            }
            //验证表单
            if(EmptyUtils.isEmpty(itripAddHotelOrderVO) ||
                    (itripAddHotelOrderVO.getHotelId() == null || itripAddHotelOrderVO.getHotelId() == 0) ||
                    (itripAddHotelOrderVO.getRoomId() == null || itripAddHotelOrderVO.getRoomId() == 0) ||
                    (itripAddHotelOrderVO.getCheckInDate() == null || itripAddHotelOrderVO.getCheckOutDate() == null)){
                return DtoUtil.returnFail("不能提交空，请填写订单信息", "100506");
            }
            //验证库存
            Map<String, Object> param = new HashMap<>();
            param.put("startTime",itripAddHotelOrderVO.getCheckInDate());
            param.put("endTime",itripAddHotelOrderVO.getCheckOutDate());
            param.put("roomId",itripAddHotelOrderVO.getRoomId());
            param.put("hotelId",itripAddHotelOrderVO.getHotelId());
            param.put("count",itripAddHotelOrderVO.getCount());

            if(!itripHotelOrderService.validateRoomStore(param)){
                return DtoUtil.returnFail("库存不足", "100507");
            }
            //封装表单属性
            ItripHotelOrder itripHotelOrder = new ItripHotelOrder();
            BeanUtils.copyProperties(itripAddHotelOrderVO, itripHotelOrder);
            //设置下单人，创建人
            ItripUser itripUser = validationToken.getCurrentUser(token);
            itripHotelOrder.setUserId(itripUser.getId());
            itripHotelOrder.setCreatedBy(itripUser.getId());
            //住店相关人员
            List<ItripUserLinkUser> linkUserList = itripAddHotelOrderVO.getLinkUser();
            if(EmptyUtils.isNotEmpty(linkUserList)){
                StringBuilder builder = new StringBuilder("");
                for(int i = 0; ; ){
                    builder.append(linkUserList.get(i).getLinkUserName());
                    if(++i < linkUserList.size()) {
                        builder.append(", ");
                        continue;
                    }
                    break;
                }
                itripHotelOrder.setLinkUserName(builder.toString());
            }
            //预订的天数
            int days = DateUtil.getBetweenDates(itripAddHotelOrderVO.getCheckInDate(),
                    itripAddHotelOrderVO.getCheckOutDate()).size() - 1;
            itripHotelOrder.setBookingDays(days);
            //订单来自哪个平台
            if(token.startsWith("token:PC-")){
                itripHotelOrder.setBookType(0);
            }else if(token.startsWith("token:MOBILE-")){
                itripHotelOrder.setBookType(1);
            }else{
                itripHotelOrder.setBookType(2);
            }
            //payType下一步再设置
            //订单状态
            itripHotelOrder.setOrderStatus(0);
            //订单号
            //机器码 + 日期 + MD5(hotelId,roomId,当前时间毫米数,百万单位随机数)取六位
            StringBuilder md5 = new StringBuilder("");
            md5.append(itripHotelOrder.getHotelId());
            md5.append(itripHotelOrder.getRoomId());
            md5.append(System.currentTimeMillis());
            md5.append(Math.random()*1000000);
            String md5Str = MD5.getMd5(md5.toString(), 6);
            StringBuilder orderBuilder = new StringBuilder("");
            orderBuilder.append(systemConfig.getMachineCode());
            orderBuilder.append(DateUtil.format(new Date(), "yyyyMMddHHmmss"));
            orderBuilder.append(md5Str);
            itripHotelOrder.setOrderNo(orderBuilder.toString());
            //订单类型
            itripHotelOrder.setOrderType(1);
            //订单金额
            itripHotelOrder.setPayAmount(itripHotelOrderService.getOrderPayAmount(
                    days * itripAddHotelOrderVO.getCount(),
                    itripAddHotelOrderVO.getRoomId()).doubleValue());
            //添加订单
            Map<String, String> result = itripHotelOrderService.itriptxAddItripHotelOrder(itripHotelOrder, itripAddHotelOrderVO.getLinkUser());
            return DtoUtil.returnDataSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            return DtoUtil.returnFail("生成订单失败", "100505");
        }
    }

    @RequestMapping(value = "/updateorderstatusandpaytype", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Dto updateOrderStatusAndPayType(@RequestBody ItripModifyHotelOrderVO itripModifyHotelOrderVO,
                                           HttpServletRequest request) throws Exception{
        try{
            String token = request.getHeader("token");
            String agent = request.getHeader("user-agent");
            if(!validationToken.validateToken(token,agent)){
                return DtoUtil.returnFail("token失效，请重新登录","100000 ");
            }
            if(itripModifyHotelOrderVO == null ||
                    (itripModifyHotelOrderVO.getId() == null || itripModifyHotelOrderVO.getId() == 0) ||
                    (itripModifyHotelOrderVO.getPayType() == null || itripModifyHotelOrderVO.getPayType() == 0)){
                return DtoUtil.returnFail("不能提交空，请填写订单信息","100523");
            }
            //验证是否支持线下支付
            if(!itripHotelOrderService.isOffLinePaymentSupported(itripModifyHotelOrderVO.getId())){
                return DtoUtil.returnFail("对不起，此房间不支持线下支付","100521");
            }
            //更新状态和支付类型
            ItripHotelOrder order = new ItripHotelOrder();
            order.setId(itripModifyHotelOrderVO.getId());
            //设置订单的支付类型
            order.setPayType(itripModifyHotelOrderVO.getPayType());
            //设置订单状态，已支付
            order.setOrderStatus(2);
            ItripUser user = validationToken.getCurrentUser(token);
            //设置修改人信息和修改时间
            order.setModifiedBy(user.getId());
            order.setModifyDate(new Date());
            //更新
            itripHotelOrderService.itriptxModifyItripHotelOrder(order);
            return DtoUtil.returnSuccess();
        }catch(Exception e){
            e.printStackTrace();
            return DtoUtil.returnFail("修改订单失败","100522");
        }
    }

    //支付成功后查询订单信息
    @RequestMapping(value = "/querysuccessorderinfo/{id}", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Dto<Map<String, Object>> querySuccessOrderInfo(@PathVariable Integer id,
                                                          HttpServletRequest request) throws Exception{
        try {
            String token = request.getHeader("token");
            String agent = request.getHeader("user-agent");
            if (!validationToken.validateToken(token, agent)) {
                return DtoUtil.returnFail("token失效，请重新登录", "100000");
            }
            if(id == null || id == 0){
                return DtoUtil.returnFail("id不能为空","100519");
            }
            ItripHotelOrder order = itripHotelOrderService.getItripHotelOrderById(Long.valueOf(id));
            if(EmptyUtils.isEmpty(order)){
                return DtoUtil.returnFail("获取数据失败","100520");
            }
            ItripHotelRoom room = itripHotelRoomService.getItripHotelRoomById(order.getRoomId());
            Map<String, Object> result = new HashMap<>();
            result.put("id", order.getId());
            result.put("orderNo", order.getOrderNo());
            result.put("payType", order.getPayType());
            result.put("payAmount", order.getPayAmount());
            result.put("hotelName", order.getHotelName());
            result.put("roomTitle", room.getRoomTitle());
            return DtoUtil.returnDataSuccess(result);
        }catch(Exception e){
            e.printStackTrace();
            return DtoUtil.returnFail("获取数据失败","100520");
        }
    }

    @RequestMapping(value = "/getpersonalorderinfo/{orderId}", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Dto<ItripPersonalHotelOrderVO> getPersonalOrderInfo(@PathVariable String orderId, HttpServletRequest request) throws Exception{
        try {
            String token = request.getHeader("token");
            String agent = request.getHeader("user-agent");
            if(!validationToken.validateToken(token,agent)){
                return DtoUtil.returnFail("token失效，请重新登录", "100000");
            }
            if(EmptyUtils.isEmpty(orderId)){
                return DtoUtil.returnFail("请传递参数：orderId","100525");
            }
            ItripHotelOrder order = itripHotelOrderService.getItripHotelOrderById(Long.valueOf(orderId));
            if(EmptyUtils.isEmpty(order)){
                return DtoUtil.returnFail("没有相关订单信息","100526");
            }
            ItripPersonalHotelOrderVO itripPersonalHotelOrderVO = new ItripPersonalHotelOrderVO();
            ItripHotelRoom room = new ItripHotelRoom();
            if(EmptyUtils.isNotEmpty(room)){
                itripPersonalHotelOrderVO.setRoomPayType(room.getPayType());
            }
            //订单状态（0：待支付 1:已取消 2:支付成功 3:已消费 4:已点评）
            //{"1":"订单提交","2":"订单支付","3":"支付成功","4":"入住","5":"订单点评","6":"订单完成"}
            //{"1":"订单提交","2":"订单支付","3":"订单取消"}
            Integer orderStatus = order.getOrderStatus();
            itripPersonalHotelOrderVO.setOrderStatus(orderStatus);
            if (orderStatus == 1) {
                itripPersonalHotelOrderVO.setOrderProcess(JSONArray.parse(systemConfig.getOrderProcessCancel()));
                itripPersonalHotelOrderVO.setProcessNode("3");
            } else if (orderStatus == 0) {
                itripPersonalHotelOrderVO.setOrderProcess(JSONArray.parse(systemConfig.getOrderProcessOK()));
                itripPersonalHotelOrderVO.setProcessNode("2");//订单支付
            } else if (orderStatus == 2) {
                itripPersonalHotelOrderVO.setOrderProcess(JSONArray.parse(systemConfig.getOrderProcessOK()));
                itripPersonalHotelOrderVO.setProcessNode("3");//支付成功（未出行）
            } else if (orderStatus == 3) {
                itripPersonalHotelOrderVO.setOrderProcess(JSONArray.parse(systemConfig.getOrderProcessOK()));
                itripPersonalHotelOrderVO.setProcessNode("5");//订单点评
            } else if (orderStatus == 4) {
                itripPersonalHotelOrderVO.setOrderProcess(JSONArray.parse(systemConfig.getOrderProcessOK()));
                itripPersonalHotelOrderVO.setProcessNode("6");//订单完成
            } else {
                itripPersonalHotelOrderVO.setOrderProcess(null);
                itripPersonalHotelOrderVO.setProcessNode(null);
            }
            itripPersonalHotelOrderVO.setId(order.getId());
            itripPersonalHotelOrderVO.setBookType(order.getBookType());
            itripPersonalHotelOrderVO.setCreationDate(order.getCreationDate());
            itripPersonalHotelOrderVO.setOrderNo(order.getOrderNo());
            itripPersonalHotelOrderVO.setPayAmount(BigDecimal.valueOf(order.getPayAmount()));
            itripPersonalHotelOrderVO.setPayType(order.getPayType());
            itripPersonalHotelOrderVO.setNoticePhone(order.getNoticePhone());
            return DtoUtil.returnDataSuccess(itripPersonalHotelOrderVO);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("获取个人订单信息错误","100527");
        }
    }

    @RequestMapping(value = "/getpersonalorderlist", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Dto<Page<ItripListHotelOrderVO>> getPersonalOrderList(@RequestBody ItripSearchOrderVO itripSearchOrderVO, HttpServletRequest request) throws Exception{
        try {
            String token = request.getHeader("token");
            String agent = request.getHeader("user-agent");
            if(!validationToken.validateToken(token,agent)){
                return DtoUtil.returnFail("token失效，请重新登录", "100000");
            }
            if(itripSearchOrderVO.getOrderType() == null){
                return DtoUtil.returnFail("请传递参数：orderType", "100501");
            }
            if(itripSearchOrderVO.getOrderStatus() == null){
                return DtoUtil.returnFail("请传递参数：orderStatus", "100502");
            }
            Map<String, Object> param = new HashMap<>();
            Integer orderType = itripSearchOrderVO.getOrderType();
            Integer orderStatus = itripSearchOrderVO.getOrderStatus();
            ItripUser currentUser = validationToken.getCurrentUser(token);//根据token获取当前用户对象，取得其用户id

            param.put("orderStatus", orderType == -1 ? null : orderType);//根据前端需求-1状态码为全部订单状态，即查询所有orderstatus的状态而不指定
            param.put("orderType", orderStatus == -1 ? null : orderStatus);//同上
            param.put("orderNo", itripSearchOrderVO.getOrderNo());
            param.put("linkUserName", itripSearchOrderVO.getLinkUserName());
            param.put("checkInDate", itripSearchOrderVO.getStartDate());
            param.put("checkOutDate", itripSearchOrderVO.getEndDate());

            Page result = itripHotelOrderService.getHotelOrderListVoPageByMap(param,
                    itripSearchOrderVO.getPageNo(),
                    itripSearchOrderVO.getPageSize());
            return DtoUtil.returnDataSuccess(result);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("获取个人订单列表错误", "100503");
        }
    }

    @RequestMapping(value = "/queryOrderById/{orderId}", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Dto<ItripModifyHotelOrderVO> queryOrderById(@PathVariable Integer orderId, HttpServletRequest request) throws Exception{
        try {
            String token = request.getHeader("token");
            String agent = request.getHeader("user-agent");
            if(!validationToken.validateToken(token,agent)){
                return DtoUtil.returnFail("token失效，请重新登录", "100000");
            }
            ItripHotelOrder order = itripHotelOrderService.getItripHotelOrderById(Long.valueOf(orderId));
            if(EmptyUtils.isEmpty(order)){
                return DtoUtil.returnFail("没有查询到相应订单", "100533");
            }
            ItripModifyHotelOrderVO itripModifyHotelOrderVO = new ItripModifyHotelOrderVO();
            BeanUtils.copyProperties(order, itripModifyHotelOrderVO);
            Map<String, Object> param = new HashMap<>();
            param.put("orderId", order.getId());
            List<ItripOrderLinkUser> linkUsers = itripOrderLinkUserService.getItripOrderLinkUserListByMap(param);
            List<ItripOrderLinkUserVo> linkUserVos = new ArrayList<>();
            BeanUtils.copyProperties(linkUsers, linkUserVos);
            itripModifyHotelOrderVO.setItripOrderLinkUserList(linkUserVos);
            return DtoUtil.returnDataSuccess(itripModifyHotelOrderVO);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("系统异常", "100534");
        }
    }

    @RequestMapping(value = "/getpersonalorderroominfo/{orderId}", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Dto<Map<String, Object>> getPersonalOrderRoomInfo(@PathVariable String orderId, HttpServletRequest request) throws Exception{
        try {
            String token = request.getHeader("token");
            String agent = request.getHeader("user-agent");
            if(!validationToken.validateToken(token,agent)){
                return DtoUtil.returnFail("token失效，请重新登录", "100000");
            }
            if(orderId == null || orderId == ""){
                return DtoUtil.returnFail("请传递参数：orderId", "100529");
            }
            Map<String, Object> result = new HashMap<>();
            ItripHotelOrder order = itripHotelOrderService.getItripHotelOrderById(Long.valueOf(orderId));
            ItripHotelRoom room = itripHotelRoomService.getItripHotelRoomById(order.getRoomId());
            if(EmptyUtils.isEmpty(room)){
                return DtoUtil.returnFail("没有相关订单房型信息", "100530");
            }
            result.put("roomId", room.getId());
            result.put("roomTitle", room.getRoomTitle());
            result.put("roomPrice", room.getRoomPrice());
            result.put("isHavingBreakfast", room.getIsHavingBreakfast());
            return DtoUtil.returnDataSuccess(result);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("获取个人订单房型信息错误", "100531");
        }
    }
}
